package com.eos.freeect.common.action;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Vector;

import org.apache.struts2.ServletActionContext;

import com.eos.freeect.common.Globals;
import com.eos.freeect.common.Utilities;
import com.eos.freeect.common.model.Login;
import com.eos.freeect.common.service.LoginService;
import com.opensymphony.xwork2.ActionSupport;
/**
 * <p>Title: LoginInput</p>
 * <p>Description: LoginInput</p>
 * <p>Copyright: Copyright (c) 2010</p>
 * <p>Company: EOS soft</p>
 * @author Eric
 * @version 1.0
 */

public class LoginAction extends ActionSupport {
	
	private static final long serialVersionUID = 4536250951500258243L;

	private Login login;
	private LoginService loginService;
	
	//登陆界面Action
	public String loginInput() {
    	// Forward to success page
        return SUCCESS;
    }
	 
	//登陆验证Action
	public String login() {
    	
	    ServletContext application = ServletActionContext.getServletContext();
	    HttpSession session = ServletActionContext.getRequest().getSession();
		
		String username = Utilities.getParameter("username");
		String userpwd = Utilities.getParameter("password");
		
		login = new Login();
		login.setUserName(username);
		login.setPassword(Utilities.getMD5(userpwd));
		
		List<Login> userList = loginService.checkPWD(login);
		
		//用户密码错误
		if(userList == null||userList.size() != 1)
		{
			String message = "\u7528\u6237\u540d,\u5bc6\u7801  \u9519\u8bef!";  //用户名,密码  错误!
			Utilities.setAttribute("message", message);
			return ERROR;
		}
		else
		{
			Login userInfo = (Login)userList.get(0);
			if (userInfo.getLimitIp()!=null && !"".equals(userInfo.getLimitIp()))
			{
				//检查登录IP是否正确
				if(userInfo.getLimitIp()!=Utilities.getUserIP())
				{
					String message = "\u8be5\u7528\u6237\u9650\u5236\u767b\u5f55IP\u4e3a\uff1a";  //该用户限制登录IP为：
					Utilities.setAttribute("message", message + userInfo.getLimitIp()); 
					return ERROR;
				}
			}
			userInfo.setNowLoginIp(Utilities.getUserIP());
			userInfo.setNowLoginTime(new java.util.Date());
			
			session.setAttribute(Globals.USERINFO_KEY, userInfo);
			
		    Vector onlineusers = (Vector) application.getAttribute(Globals.USERINFOS_KEY);
		    if (onlineusers == null) {
		    	onlineusers = new Vector();
		    	application.setAttribute(Globals.USERINFOS_KEY, onlineusers);
		    }
		    
		    for (int i = 0; i < onlineusers.size(); i++) {
		        Login loginUser = (Login) onlineusers.elementAt(i);

		        String userId = loginUser.getUserId();

		         //用户已登陆
		        if (userInfo.getUserId().equals(userId)) {
		        	if (!Utilities.getUserIP().equals(loginUser.getNowLoginIp()))
		        	{
			        	Utilities.setAttribute("message", "\u8be5\u7528\u6237\u5df2\u7ecf\u5728\u5176\u4ed6\u5730\u65b9\u767b\u9646!"); //该用户已经在其他地方登陆!
			            return ERROR;		        		
		        	}
		        	else
		        	{
		        		onlineusers.remove(loginUser);
		        	}
		        }
		    }
		    //添加在线用户
		    onlineusers.add(userInfo);
		    
		    try {
			    Login logUser = new Login();
				Utilities.setBeanValue(userInfo,logUser);
			    logUser.setLastLoginIp(logUser.getNowLoginIp());
			    logUser.setLastLoginTime(logUser.getNowLoginTime());
			    loginService.updateUserInfo(logUser);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// Forward to success page
	        return SUCCESS;
		}
    }
	
	//滚动条Action
	public String getRightBar() {
    	// Forward to success page
		String MARQUEE_KEY = "com.eos.freeect.common.announcement.marquee";
		Utilities.setAttribute(MARQUEE_KEY, loginService.getAnnouncementListMarquee());

		return SUCCESS;
    }
	
	//公告Action
	public String getAnnouncementList() {
    	// Forward to success page
		Utilities.setAttribute("anouncementlist", loginService.getAnnouncementList());

		return SUCCESS;
    }		
	
	//左上角Action
	public String getLeftBar() {
	    ServletContext application = ServletActionContext.getServletContext();
	    HttpSession session = ServletActionContext.getRequest().getSession();
	    
	    Login loginUser = (Login)session.getAttribute(Globals.USERINFO_KEY);
	    
		String userIcon = "";
		String headPic = loginUser.getFacePic();
		if(headPic==null||"".equals(headPic)){
		    userIcon = "images/template/default/icon-user.jpg";
		}
		else{
		    userIcon = "images/headpic/" + headPic;
		}
		  
		String userName = loginUser.getNickName();
		if(userName==null||"".equals(userName)){
		    userName = loginUser.getUserName();
		}
		
		java.util.Date lastLoginTime = loginUser.getLastLoginTime();
		String remind = "\u60a8\u6ca1\u6709\u65b0\u7684\u63d0\u9192";
		 
		if(lastLoginTime != null){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			remind = "\u60a8\u4e0a\u6b21\u767b\u5f55\u65f6\u95f4\u662f" + sdf.format(lastLoginTime);
		}
		
		Calendar cal = Calendar.getInstance();
		String greetings = "";
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		if (hour >= 6 && hour < 8) {
			greetings = "\u65e9\u4e0a\u597d";  //早上好
		} else if (hour >= 8 && hour < 12) {
			greetings = "\u4e0a\u5348\u597d";  //上午好
		} else if (hour >= 12 && hour < 13) {
			greetings = "\u4e2d\u5348\u597d";  //中午好
		} else if (hour >= 13 && hour < 18) {
			greetings = "\u4e0b\u5348\u597d";  //下午好
		} else {
			greetings = "\u665a\u4e0a\u597d";  //晚上好
		}
			
		Utilities.setAttribute("username", userName);
		Utilities.setAttribute("usericon", userIcon);
		Utilities.setAttribute("onlinenumber", ((Vector)application.getAttribute(Globals.USERINFOS_KEY)).size());
		Utilities.setAttribute("remind", remind);
		Utilities.setAttribute("greetings", greetings);
		
    	// Forward to success page
        return SUCCESS;
    }
	
	//首页Action
	public String getWelcome() {
    	// Forward to success page
        return SUCCESS;
    }	
	
	//左边菜单栏Action
	public String getLeftMenu() {
        StringBuffer buf = new StringBuffer();

        buf.append("<tree id=\"0\"> \n");
        
        buf.append("<item text=\"首页\" id=\"index\" select=\"1\"> \n");
        buf.append("<userdata name=\"thisurl\">common/welcome.eos</userdata> \n");
        buf.append("</item>   \n");
        
        buf.append("<item text=\"公共模块\" open=\"1\" id=\"common\" > \n");
        buf.append("<item text=\"公告栏\" id=\"announcement\" > \n");
        buf.append("<userdata name=\"thisurl\">common/view-announcement-list.eos</userdata> \n");
        buf.append("</item>   \n"); 
        buf.append("</item>   \n"); 
        
        buf.append("<item text=\"注销\" id=\"logout\" > \n");
        buf.append("<userdata name=\"thisurl\">common/logout.eos</userdata> \n");
        buf.append("</item>   \n"); 
        
        
        buf.append("</tree>  \n");      
        
        Utilities.setAttribute("menustr",buf.toString());
		
    	// Forward to success page
        return SUCCESS;
    }
	
	//注销Action
	public String logout() {
	    try{
		    ServletContext application = ServletActionContext.getServletContext();
		    HttpSession session = ServletActionContext.getRequest().getSession();
		    
		    Login userInfo = (Login) session.getAttribute(Globals.USERINFO_KEY);
	    	Vector onlineusers = (Vector) application.getAttribute(Globals.USERINFOS_KEY);

	    	onlineusers.remove(userInfo);
	    	session.invalidate();
	    }catch(Exception e){
	        e.printStackTrace();
	    }
    	// Forward to success page
        return SUCCESS;
    }
	
	//在线用户列表Action
	public String viewOnlineUsers() {
    	// Forward to success page
		ServletContext application = ServletActionContext.getServletContext();
		Vector onlineusers = (Vector) application.getAttribute(Globals.USERINFOS_KEY);
		
		Utilities.setAttribute("onlineusers", onlineusers);

		return SUCCESS;
    }		

	public Login getLogin() {
		return login;
	}

	public void setLogin(Login login) {
		this.login = login;
	}
	
	public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
	
}
